package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.exception.ExceptionCatch.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.jni.User;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Value("%file.oss.web-site")
    private String webSite;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    WmNewsMapper wmNewsMapper;
    @Autowired
    private  WmUserMapper wmUserMapper;
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //1 参数检查
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2 条件封装执行查询
        Page<WmNews> pageReq = new Page<>(dto.getPage(), dto.getSize());//分页查询
        // 文章标题模糊查询
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.lambdaQuery();
        String keyword = dto.getKeyword();
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.like(WmNews::getTitle, keyword);
        }
//            wrapper.like(StringUtils.isNotBlank(keyword),WmNews::getTitle,keyword);
        // 频道id
        Integer channelId = dto.getChannelId();
        if (channelId != null) {
            wrapper.like(WmNews::getChannelId, channelId);
        }

        // 文章状态
        Short status = dto.getStatus();
        if (status != null) {
            wrapper.like(WmNews::getStatus, status);
        }
        // 发布时间 >= 开始时间
        Date beginPubDate = dto.getBeginPubDate();
        // 发布时间 <= 开始时间
        Date endPubDate = dto.getEndPubDate();
        if (beginPubDate != null && endPubDate != null) {
            wrapper.between(WmNews::getPublishTime, beginPubDate, endPubDate);
        }
        // 分页条件构建
        wrapper.eq(WmNews::getId, user.getId());
        wrapper.orderByDesc(WmNews::getPublishTime);
        //3 执行查询
        IPage<WmNews> pageResult = page(pageReq, wrapper);
        //4 返回封装查询结果
        PageResponseResult result = new PageResponseResult(dto.getPage(),
                dto.getSize(),
                pageResult.getTotal(),
                pageResult.getRecords());
        result.setHost(webSite);
        return result;
    }

    /**
     * 保存或修改文章
     *
     * @param wmNews 文章对象（前端传递）
     */
    private void saveWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP); // 上架
        if (wmNews.getId() == null) { // 保存操作
            save(wmNews);
        } else {  // 修改
            // 当前文章 和 素材关系表数据删除
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }


    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        //1.抽取dto为wmNews对象
        WmNews wmNews = getWmNews(dto);
        //2.保存或者修改文章
        saveUpdatewmNews(wmNews);
        //如果当前文章是草稿 不需要保存关联关系
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())){
            return ResponseResult.okResult();
        }

        //3.保存文章和素材的关联关系
        // TODO 3.1 抽取文章中关联的图片路径
        List<String> materialUrls = parseContentImages(wmNews.getContent());
        // TODO 3.2 关联文章内容中的图片和素材关系
        if (CollectionUtils.isEmpty(materialUrls)) {
            saveRelativeInfo(materialUrls, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }
        // TODO 3.3 关联文章封面中的图片和素材关系  封面可能是选择自动或者是无图
        saveRelativeInfoForCover(dto, materialUrls, wmNews);
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送文章自动审核消息，当前待审核的文章id==>{}",wmNews.getId());


        return ResponseResult.okResult();


    }

    //保存封面和素材的关联关系
    private void saveRelativeInfoForCover(WmNewsDTO dto, List<String> materialUrls, WmNews wmNews) {
        List<String> images = dto.getImages();
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            int size = materialUrls == null ? 0 : materialUrls.size();
            if (size>0&&size<=2){
                //单图
                images = materialUrls.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else if (size>2){
                //多图
                images = materialUrls.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            wmNews.setImages(imageListToStr(images));
            this.updateById(wmNews);
        }
        //保存封面与素材的关联关系
        if (!CollectionUtils.isEmpty(images)){
            //再替换一次前缀路径
            images=images.stream().map(url->url.replaceAll(webSite,"")).collect(Collectors.toList());
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
        }

    }

    private void saveRelativeInfo(List<String> materialUrls, Integer newsId, Short type) {
        //1 根据素材路径列表和当前登录用户id查询出素材id集合
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
                Wrappers.<WmMaterial>lambdaQuery()
                        .in(WmMaterial::getUrl, materialUrls)
                        .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
                        .select(WmMaterial::getId)
        );
        if (materialUrls.size() != wmMaterials.size()) {
            //素材丢失
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "素材缺失，保存失败");
        }
        for (WmMaterial wmMaterial : wmMaterials) {
            //批量保存关联关系
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(wmMaterial.getId());
            wmNewsMaterial.setNewsId(newsId);
            wmNewsMaterial.setType(type);
            wmNewsMaterialMapper.insert(wmNewsMaterial);
        }
    }
    //2.判断传入路径的数量和素材id的数量一致  如果不一致说明缺少素材
    //3.将素材id 文章id 路径 插入


    //抽取文章内容中所有的素材路径   要去除前缀 去除重复的返回路径集合
    private List<String> parseContentImages(String content) {
        List<Map> maplist = JSON.parseArray(content, Map.class);
        maplist.stream().filter(m -> WemediaConstants.WM_NEWS_MANY_IMAGE.equals(m.get("key")))
                //获取map中value的值  是素材完整路径
                .map(m -> String.valueOf(m.get("value")))
                //替换wesite前缀
                .map(url -> url.replaceAll(webSite, ""))
                //去重
                .distinct()
                .collect(Collectors.toList());

        return null;
    }

    private void saveUpdatewmNews(WmNews wmNews) {
        //如果有文章di就修改没有就保存
        if (wmNews.getId() == null) {
            this.save(wmNews);
        } else {
            //先删除文章和素材的关联关系
            wmNewsMaterialMapper.delete
                    (Wrappers.<WmNewsMaterial>lambdaQuery().
                            eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            //如果有文章id就修改
            updateById(wmNews);
        }
    }


    private WmNews getWmNews(WmNewsDTO dto) {
        //1.将前端传过来的dto封装成News对象以供操作
        //参数校验 内容标题不为空 是否登录
        if (StringUtils.isBlank(dto.getContent()) || StringUtils.isBlank(dto.getTitle())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章不能为空");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "登录之后才能发布文章");
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }

        wmNews.setImages(imageListToStr(dto.getImages()));
        //设置登录用户id
        wmNews.setUserId(user.getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        return wmNews;
    }
    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if(id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    //将封面集合转化为字符串    全路径wbeSite  +  url1    +url2   +url3
    private String imageListToStr(List<String> images) {
        if (CollectionUtils.isEmpty(images)) {
            return null;
        }
        return  //获取流
                images.stream()
                        //用map映射方法  替换掉每一个前缀
                        .map(url -> url.replaceAll(webSite, ""))
                        //终止  收集之后用逗号拼接字符串
                        .collect(Collectors.joining(","));
    }


    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());

        if(StringUtils.isNotBlank(dto.getTitle())){
            //  concat(%,?,%)
            dto.setTitle("%"+dto.getTitle()+"%");
        }

        //2.分页查询
        List<WmNewsVO> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;
    }
    /**
     * 查询文章详情
     * @param id
     * @return
     */

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

}
